package com.redxiii.safesync;

import java.io.File;
import java.io.IOException;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.redxiii.safesync.container.RemoteContainer;
import com.redxiii.util.gui.InstallConfigGui;
import com.redxiii.util.gui.actions.AlertSystem;
import com.redxiii.util.gui.actions.NextAction;
import com.redxiii.util.gui.config.Frame;

public class SyncHandlerGraphical extends SyncHandler {

	private static final Logger logger = LoggerFactory.getLogger(SyncHandlerGraphical.class);
	
	
	@Override
	protected void getConfiguration() {
		
		File preferences = new File("preferences.properties");
		try {
			if (!preferences.exists())
				preferences.createNewFile();
			
			config = new PropertiesConfiguration(preferences);
		} catch (ConfigurationException e) {
			logger.error("Fail loading configuration file",e);
		} catch (IOException e) {
			logger.error("Fail creating configuration file",e);
		}
				
		Frame frame = new Frame("Safe Storage Synchronization Tool", config)
			.createField("local", "Local Directory (raw)")
			.createField("remote", "Remote directory (encrypted)")
			.createField("direction", SyncDirection.class, "Direction")
			.createField("password", "Password")
			.setAction(new NextAction() {
				public boolean next(Frame frame, AlertSystem alertSystem) {
					return checkConfig(alertSystem);
				}
				
				public String getProgressStatus() {
					return null;
				}
			});
		
		logger.debug("Create Graphical Interface");
		new InstallConfigGui(frame, "Safe Storage Synchronization Tool").run();
		
		logger.debug("Configuration done");
	}
	
	private boolean checkConfig(AlertSystem alertSystem) {
		File fLocal = new File(config.getString("local"));
		File fRemote = new File(config.getString("remote"));
		
		if (!fLocal.exists()) {
			alertSystem.alert("Local Directory does not exist");
			return false;
		}
		
		if (!fLocal.isDirectory()) {
			alertSystem.alert("'" + config.getString("local") + "' is not a directory");
			return false;
		}
		
		if (!fRemote.exists()) {
			alertSystem.alert("Remote Directory does not exist");
			return false;
		}
		
		if (!fRemote.isDirectory()) {
			alertSystem.alert("'" + config.getString("local") + "' is not a directory");
			return false;
		}
		
		try {
			RemoteContainer.verifyContainer(fRemote, new CryptoToolWithGZip(config.getString("password")));
		} catch(Exception e) {
			logger.error("Invalid password. \"{}\" ",e.getMessage());
			alertSystem.alert("Invalid password");
			return false;
		}
		
		return true;
	}
	
	public static void main(String[] args) {
		new SyncHandlerGraphical().sync();
	}
}
